package com.uxhuanche.ui.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import com.uxhuanche.ui.R;


public class ButtonWithTimer extends AppCompatTextView implements Handler.Callback {
    Handler mHandler;

    int retryTime;
    String format;
    String orgStr;
    int count;

    private OnTimerListener mListener;

    public ButtonWithTimer(Context context) {
        super(context);
    }

    public ButtonWithTimer(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ButtonWithTimer);
        retryTime = a.getInteger(R.styleable.ButtonWithTimer_ButtonWithTimer_time, 60);
        format = a.getString(R.styleable.ButtonWithTimer_ButtonWithTimer_show_timer_str_format);
        format = format == null ? "重试(%02d秒)" : format;
        orgStr = getText().toString();
        a.recycle();

        mHandler = new Handler(this);
    }


    public void setListener(OnTimerListener listener) {
        this.mListener = listener;
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (!enabled) {
            count = retryTime;
            mHandler.sendEmptyMessage(count);
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what <= 0) {
            setText(orgStr);
            setEnabled(true);
            if (null != mListener) {
                mListener.timerEnd();
            }
        } else {
            setText(String.format(format, count--));
            mHandler.sendEmptyMessageDelayed(count, 1000);
        }
        return true;
    }


    public interface OnTimerListener {
        void timerEnd();
    }
}
